﻿using MySql.Simple.Mapper.Finders;
using MySql.Simple.Mapper.Structures;

namespace MySql.Simple.Mapper.Commands.Rows
{
    /// <summary>
    /// Writes the contents of the given object into the database.
    /// </summary>
    public static class UpdateCommand
    {
        private const string Sql = @"UPDATE `{0}` SET {1} WHERE `{2}` = {3};";

        /// <summary>
        /// Writes the contents of the given object into the database.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="result">The result.</param>
        /// <param name="connection">The connection.</param>
        public static void Update<T>(T result, Connection connection)
        {
            var tableName = TableNameFinder.Find(typeof(T));
            var columns = ColumnFinder.Find(typeof(T), result);

            // Execute 
            connection.ExecuteNonQuery(Sql, 
                                       columns.ToDbParameters(), 
                                       tableName, 
                                       columns.ToUpdateColumnsSql(), 
                                       columns.PrimaryKeyName, 
                                       columns.PrimaryKeyValue);
        }
    }
}